package com.winapi.winapigateway;

import com.winapi.winapiclientsdk.utils.SignUtils;
import com.winapi.winapicommon.model.entity.InterfaceInfo;
import com.winapi.winapicommon.model.entity.User;
import com.winapi.winapicommon.service.InnerInterfaceInfoService;
import com.winapi.winapicommon.service.InnerUserInterfaceInfoService;
import com.winapi.winapicommon.service.InnerUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 全局过滤
 * @author yyzhang
 * @version 1.0
 */
@Slf4j
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {
    @DubboReference
    private InnerUserInterfaceInfoService innerUserInterfaceInfoService;
    @DubboReference
    private InnerUserService innerUserService;
    @DubboReference
    private InnerInterfaceInfoService innerInterfaceInfoService;
    //1.用户发送请求到API网关【已完成，过滤器所有请求都经过】

    //白名单
private static final List<String> IP_WHITE_LIST= Arrays.asList("localhost");
    //private static final String INTERFACE_HOST= "http://47.120.4.160:8123";
    private static final String INTERFACE_HOST= "http://localhost:8123";
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //2.请求日志
        ServerHttpRequest request= exchange.getRequest();
        String path =INTERFACE_HOST+request.getPath().value();
        String method = request.getMethod().toString();
        log.info("请求唯一标识："+request.getId());
        log.info("请求路径："+path);
        log.info("请求方法："+method);
        log.info("请求参数："+request.getQueryParams());
        String sourcePath = request.getLocalAddress().getHostString();
        log.info("请求来源地址："+sourcePath);
        log.info("请求来源地址："+request.getRemoteAddress());
        log.info("custom global filter");
        //3.(黑白名单) 尽量用白名单
          ServerHttpResponse response = exchange.getResponse();
//        if(!IP_WHITE_LIST.contains(sourcePath)){
//            response.setStatusCode(HttpStatus.FORBIDDEN);//403,请求被拒绝
//            return response.setComplete();
//        }
        //4。用户鉴权（判断ak、sk是否合法）
         HttpHeaders headers = request.getHeaders();
        String accessKey = headers.getFirst("accessKey");
        String sign = headers.getFirst("sign");
        String nonce =headers.getFirst("nonce");
        String timestamp = headers.getFirst("timestamp");
        String body=headers.getFirst("body");
        //from database to authroize user
        User invokeUser =null;
        try{
            invokeUser= innerUserService.getInvokeUser(accessKey);
        }catch(Exception e){
            log.error("getInvokeUser error",e);
        }
        if (invokeUser ==null){
            return handleNoAuth(response);
        }

        if(Long.parseLong(nonce)>10000){
            return handleNoAuth(response);
        }
        //时间和当前时间不能超过5分钟
        Long currentTime=System.currentTimeMillis()/1000;
        final Long FIVE_MINUTES =60* 5L;
        if ((currentTime- Long.parseLong(timestamp))>=FIVE_MINUTES){
            return handleNoAuth(response);
        }


        //实际情况中是从数据库中查出secretKey
        String secretKey =invokeUser.getSecretKey();
        String sign1 = SignUtils.getSign(body, secretKey);
        if(sign1==null||!sign1.equals(sign)){
            return handleNoAuth(response);
        }
        //5。请求的模拟接口是否存在,以及请求方法是否匹配
        InterfaceInfo interfaceInfo =null;
        try{
            interfaceInfo = innerInterfaceInfoService.getInterfaceInfo(path, method);
        }catch(Exception e){
            log.error("getInterfaceInfo error",e);
        }
        if (interfaceInfo ==null){
            return handleNoAuth(response);
        }
        //todo
        //6。清求转发，调用模拟接口+响应日志
        //预期是等模拟接口调用完成，才记录响应日志、统计调用次数。
        //但现实是chain.filter方法立刻返回了，直到filter过滤器return后才调用了模拟接口。
        //原因是：chain.filter是个异步操作，理解为前端的promise
        //现在使用装饰者模式来增强这个方法。
        /* Mono<Void> filter=chain.filter(exchange);
         //7.调用成功之后要输入一个响应日志
        return filter;
        */
        //是否还有调用次数
        boolean b =false;
        try {
           b= innerUserInterfaceInfoService.enableInvoke(interfaceInfo.getId(), invokeUser.getId());
        }catch(Exception e){
            log.error("无请求次数 error",e);
        }
        if (!b) {
            return handleNoAuth(response);
        }
        return handleResponse(exchange,chain,interfaceInfo.getId(),invokeUser.getId());

    }
    public Mono<Void> handleNoAuth(ServerHttpResponse response){
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return response.setComplete();
    }
    public Mono<Void> handleInvokeError(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        return response.setComplete();
    }
    @Override
    public int getOrder() {
        return -1;
    }
    public Mono<Void> handleResponse(ServerWebExchange exchange,GatewayFilterChain chain,long interfaceInfoId,long userId)
    {
        try {
            ServerHttpResponse originalResponse = exchange.getResponse();
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();

            HttpStatus statusCode = originalResponse.getStatusCode();

            if(statusCode == HttpStatus.OK){
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {

                    @Override
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        //log.info("body instanceof Flux: {}", (body instanceof Flux));
                        if (body instanceof Flux) {
                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                            //
                            return super.writeWith(fluxBody.map(dataBuffer -> {
                                //8。调用成功，接口调用次数+1
                                try{
                                    innerUserInterfaceInfoService.invokeCount(interfaceInfoId,userId);
                                }catch (Exception e){
                                    log.error("invokeCount error",e);
                                }
                                byte[] content = new byte[dataBuffer.readableByteCount()];
                                dataBuffer.read(content);
                                DataBufferUtils.release(dataBuffer);//释放掉内存
                                // 构建日志
                                StringBuilder sb2 = new StringBuilder(200);
                                List<Object> rspArgs = new ArrayList<>();
                                rspArgs.add(originalResponse.getStatusCode());
                                //rspArgs.add(requestUrl);
                                String data = new String(content, StandardCharsets.UTF_8);//data
                                sb2.append(data);
                                //打印日志
                                log.info("响应结果："+data);
                                return bufferFactory.wrap(content);
                            }));
                        } else {
                            log.error("网关处理响应异常", getStatusCode());
                        }
                        return super.writeWith(body);
                    }
                };
                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }
            return chain.filter(exchange);//降级处理返回数据
        }catch (Exception e){
            log.error("gateway log exception.\n" + e);
            return chain.filter(exchange);
        }
    }
}
